package com.fyb.basic.juc.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author：MR.FANG
 * @name：ConditionDemo
 * 共享数据 交替打印  1 0 1 0 1 0
 * @Date：2025/7/2 下午3:49
 */
public class ConditionDemo {
    private int num = 0;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {
        try {
            lock.lock();
            while (num != 0){
                condition.await();
            }
            num++;
            System.out.println("线程名称："+Thread.currentThread().getName() + "\t" + "数量："+num);
            condition.signalAll();
        } finally {
            lock.unlock();
        }


    }

    //
    public void decrement() throws InterruptedException {
        try {
            lock.lock();
            while (num != 1){
                condition.await();
            }
            num--;
            System.out.println("线程名称："+Thread.currentThread().getName() + "\t" + "数量："+num);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        ConditionDemo shareDataDemo = new ConditionDemo();
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    shareDataDemo.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    shareDataDemo.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }

    }
}
